define(['jquery', 'bootstrap', 'backend', 'table', 'form'], function ($, undefined, Backend, Table, Form) {

    var Controller = {
        index: function () {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'resources/tag/index',
                    add_url: 'resources/tag/add',
                    edit_url: 'resources/tag/edit',
                    del_url: 'resources/tag/del',
                    multi_url: 'resources/tag/multi',
                    table: 'region',
                }
            });

            var table = $("#table");

            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'id',
                sortName: 'id',
                columns: [
                    [
                        {checkbox: true},
                        {field: 'id', title: __('ID')},
                        {field: 'tagtype.id', title: __('标签类型'), visible:false,searchList: $.getJSON("resources/tag/source")},
                        {field: 'tagtype.name', title: __('标签类型'),operate:false},
                        {field: 'tagtype.flag', title: __('标签类型标识'),operate:'LIKE',placeholder: __('模糊查询'),formatter: function(value,row,index){
                            if(value){
                                return value;
                            }else{
                                return '-';
                            }
                            
                        }},
                        {field: 'name', title: __('标签名称'),operate:'LIKE',placeholder: __('模糊查询')},
                        {field: 'comment', title: __('备注'),operate:'LIKE',placeholder: __('模糊查询'),formatter:function(value,row,index){
                            if(value){
                                return value;
                            }else{
                                return '-';
                            }
                        }},
                        // {
                        //     field: 'name', title: __('标签名称'),
                        //     formatter: Controller.api.formatter.tag, table: table, events: {
                        //     'click .labelhref': function (e, value, row) {
                        //         Backend.api.addtabs("/admin/resources/resc/label?tag_id=" + row.id+"&name="+row.tag_type.name+"-"+row.name, '标签详情', 'fa fa-bandcamp');
                        //     }
                        // }
                        // },
                        // {field: 'name', title: __('标签名称'),operate:'LIKE',placeholder: __('模糊查询'),formatter:function (value,row,index) {
                        //     // console.log(row);
                        //     return '<a title="点击查看详情" class="btn btn-xs btn-primary" href="/admin/resources/resc/label?tag_id='+row.id+'&name='+row.tag_type.name+'-'+row.name+'">'+row.name+'</a>';
                        // }},
                        // {field: 'tag', title: __('Tag'),operate:'LIKE',placeholder: __('模糊查询')},
                        // {field: 'content', title: __('Content'),operate:'LIKE',placeholder: __('模糊查询')},
                        {field: 'createtime', title: __('创建时间'), operate:'RANGE', addclass:'datetimerange', formatter: Table.api.formatter.datetime},
                        {field: 'updatetime', title: __('更新时间'), operate:'RANGE', addclass:'datetimerange', formatter: Table.api.formatter.datetime},
                        {field: 'operate', title: __('Operate'), table: table, events: Table.api.events.operate, formatter: Table.api.formatter.operate,
                            buttons: [
                                // {

                                //     name: 'addtabs',
                                //     text: '详情',
                                //     title: '详情',
                                //     classname: 'btn btn-xs btn-info btn-addtabs',
                                //     icon: 'fa fa-folder-o',
                                //     url: '/admin/resources/resc/label?name=1'
                                // //     name: 'detail',
                                // //     text: __('推送到屏幕'),
                                // //     title: __('推送到屏幕'),
                                // //     classname: 'btn btn-xs btn-primary btn-dialog',
                                // //     icon: 'fa fa-list',
                                // //     url: 'resources/tag/add_screen?from=tag',
                                // //     callback: function (data) {
                                // //         Layer.alert("接收到回传数据：" + JSON.stringify(data), {title: "回传数据"});
                                // //     },
                                // //     visible: function (row) {
                                // //         //返回true时按钮显示,返回false隐藏
                                // //         return true;
                                // //     }
                                //  }
                                {
                                    name: 'detail',
                                    text: '绑定',
                                    title: '绑定设备接口',
                                    classname: 'btn btn-xs btn-success btn-dialog',
                                    icon: 'fa fa-plus',
                                    url: 'resources/tag/if_edit', 
                                    callback: function (data) {
                                        Layer.alert("接收到回传数据：" + JSON.stringify(data), {title: "回传数据"});
                                    },
                                    visible: function (row) {
                                        Layer.closeAll();
                                        //返回true时按钮显示,返回false隐藏
                                        return true;
                                    }                              
                                },{
                                    name: 'if_del',
                                    text: '解绑',
                                    title: '解绑设备接口',
                                    classname: 'btn btn-xs btn-danger btn-dialog',
                                    icon: 'fa fa-trash',
                                    url: 'resources/tag/if_del',                             
                                },{
                                    name: 'addtabs',
                                    text: '标签监控',
                                    title: '标签监控',
                                    icon: 'fa fa-pie-chart',  
                                    classname: 'btn btn-xs btn-info btn-addtabs',
                                    url: 'region/tag/index',

                                }
                            ],formatter: function (value, row, index) {
                                var that = $.extend({},this);
                                // console.log(row);
                                // console.log(row.tag_type.name);
                                if(row.tagtype){
                                    if(row.tagtype.flag == 'resourcetype'){                                    
                                        if(row.name == '服务器吐流' || row.name == '互联网出口') {
                                            // console.log(row.name);
                                            $(table).data("operate-edit",null);
                                            $(table).data("operate-del",null);
                                        }else{
                                            $(table).data("operate-edit",true);
                                            $(table).data("operate-del",true);
                                        }
                                    }else if(row.tagtype.flag == 'export'){
                                        if(row.name == '缓存流量' || row.name == '缓存流量回源') {
                                            $(table).data("operate-edit",null);
                                            $(table).data("operate-del",null);
                                        }else{
                                            $(table).data("operate-edit",true);
                                            $(table).data("operate-del",true);
                                        }
                                    }else{
                                        $(table).data("operate-edit",true);
                                        $(table).data("operate-del",true);
                                    }
                                }
                                if(row.iftag&&row.tagtype.flag != 'region'){//有绑定标签且非局点类型有标签监控
                                   $(table).data("operate-addtabs",true);
                                }else{
                                   $(table).data("operate-addtabs",null);
                                }
                                that.table = table;                           
                                return Table.api.formatter.operate.call(this, value, row, index);
                            }}
                    ]
                ]
            });



            // 为表格绑定事件
            Table.api.bindevent(table);
        },
        add: function () {
            Controller.api.bindevent();
            /*$('select[name="row[tag_type_id]"').on('change',function(){
                var type_str=$('select[name="row[tag_type_id]"]').find("option:selected").text();
                if(type_str=='局点统计'){
                    $('#c-name').attr("disabled","disabled");
                    document.getElementById("regiondiv").style.display="";
                    document.getElementById("statisdiv").style.display="";
                    $('select[name="row[statis_id]"]').val("1");
                    $('select[name="row[region_id]"]').val("1");
                    var region_str=$('select[name="row[region_id]"]').find("option:selected").text();
                    var statis_str=$('select[name="row[statis_id]"]').find("option:selected").text();
                    $('input[name="row[name]"]').val(region_str+"-"+statis_str);

                }else{
                    $('#c-name').removeAttr("disabled");
                    document.getElementById("regiondiv").style.display="none";
                    document.getElementById("statisdiv").style.display="none";
                    $('#c-name').val("");
                }
            });
            $('select[name="row[region_id]"').on('change',function(){
                var region_str=$('select[name="row[region_id]"]').find("option:selected").text();
                var statis_str=$('select[name="row[statis_id]"]').find("option:selected").text();
                $('input[name="row[name]"]').val(region_str+"-"+statis_str);
            });
            $('select[name="row[statis_id]"').on('change',function(){
                var region_str=$('select[name="row[region_id]"]').find("option:selected").text();
                var statis_str=$('select[name="row[statis_id]"]').find("option:selected").text();
                $('input[name="row[name]"]').val(region_str+"-"+statis_str);
            });*/   
        },
        add_screen: function () {
            Controller.api.bindevent();

        },
        edit: function () {
            Controller.api.bindevent();
            /*var type_str=$('select[name="row[tag_type_id]"]').find("option:selected").text();
            if(type_str=='局点统计'){
                $('#c-name').attr("disabled","disabled");
                $('#c-meal').attr("disabled","disabled");
                $('select[name="row[statis_id]"]').attr("disabled","disabled");
                $('select[name="row[region_id]"]').attr("disabled","disabled");
                document.getElementById("regiondiv").style.display="";
                document.getElementById("statisdiv").style.display="";
            }else{
                $('#c-name').removeAttr("disabled");
                document.getElementById("regiondiv").style.display="none";
                document.getElementById("statisdiv").style.display="none";
            }
            $('select[name="row[tag_type_id]"').on('change',function(){
                var type_str=$('select[name="row[tag_type_id]"]').find("option:selected").text();
                if(type_str=='局点统计'){
                    $('#c-name').attr("disabled","disabled");
                    document.getElementById("regiondiv").style.display="";
                    document.getElementById("statisdiv").style.display="";
                    $('select[name="row[statis_id]"]').val("1");
                    $('select[name="row[region_id]"]').val("1");
                    var region_str=$('select[name="row[region_id]"]').find("option:selected").text();
                    var statis_str=$('select[name="row[statis_id]"]').find("option:selected").text();
                    $('input[name="row[name]"]').val(region_str+"-"+statis_str);
                }else{
                    $('#c-name').removeAttr("disabled");
                    document.getElementById("regiondiv").style.display="none";
                    document.getElementById("statisdiv").style.display="none";
                    $('#c-name').val("");
                }
            });
            $('select[name="row[region_id]"').on('change',function(){
                var region_str=$('select[name="row[region_id]"]').find("option:selected").text();
                var statis_str=$('select[name="row[statis_id]"]').find("option:selected").text();
                $('input[name="row[name]"]').val(region_str+"-"+statis_str);
            });
            $('select[name="row[statis_id]"').on('change',function(){
                var region_str=$('select[name="row[region_id]"]').find("option:selected").text();
                var statis_str=$('select[name="row[statis_id]"]').find("option:selected").text();
                $('input[name="row[name]"]').val(region_str+"-"+statis_str);
            });*/
        },
        if_edit: function () {
            Controller.api.bindevent();
            $("#c-device_id").data("params",function(obj){
                return {row:{device_id:$("#deviceid").val(),type:$("input[name='row[type]']:checked").val()}};
            });
            $("input[name='row[type]']").change(function(){
                /*$('.selectpicker').selectpicker('val', ['-1']);//默认选中*/
                 //var selec = $('select[name="row[tag_id]');
                 //selec.options[0].selected = true;
                $("select[name='row[tag_id]'] option:first").prop("selected", 'selected');
                $(".selected_tag").remove();
                $("#c-device_id").val("");
                $("*deviceid").selectpicker('destroy');
                $('#deviceid').empty();
                var select = $("#deviceid"); 
                $.each(deviceList,function(k2,v2){
                       select.append("<option value='"+k2+"'>"
                      + v2 + "</option>"); 
                });
                $("#deviceid").selectpicker('refresh');
            });
            $('select[name="row[tag_id]').on('change',function(){
                $('#deviceid').selectpicker('destroy');
                $('#deviceid').empty();
                var tagtypename_str = $('select[name="row[tag_id]"]').val();
                if(tagtypename_str!=null&&tagtypename_str!=""){
                    $('select[name="row[device_id]"]').removeAttr("disabled");
                    $.ajax({
                        type:"POST",
                        url: 'resources/tag/getbytagid',
                        data:{tag_id:$(this).val()},
                        dataType:"json",
                        success:function(data){
                            var select = $("#deviceid"); 
                            $(".selectpicker").selectpicker('deselectAll');
                            for(var item of data.list) {
                               select.append("<option value='"+item.id+"'>"
                                  + item.name + "</option>"); 
                            } 
                            
                        }
                    });
                }else{
                    $('select[name="row[device_id]"]').attr("disabled","disabled");
                    $("#deviceid").append('<option value="-1" >' + '选择' + '</option>');
                }
                $('.selectpicker').selectpicker('val', ''); 
                $('.selectpicker').selectpicker('refresh');  
            });
           
        },
        if_del: function(){
            Controller.api.bindevent();
            $('#checks').click(()=>{
                if($("#checks").is(":checked")){
                    var test = document.getElementsByName("test[]");
                    for (var i = 0; i < test.length; i++) {
                        test[i].checked = true;
                    }
                }else{
                    var test = document.getElementsByName("test[]");
                    for (var i = 0; i < test.length; i++) {
                        test[i].checked = false;
                    }
                }
            })
            $('#checks1').click(()=>{
                if($("#checks1").is(":checked")){
                    var test = document.getElementsByName("test1[]");
                    for (var i = 0; i < test.length; i++) {
                        test[i].checked = true;
                    }
                }else{
                    var test = document.getElementsByName("test1[]");
                    for (var i = 0; i < test.length; i++) {
                        test[i].checked = false;
                    }
                }
            })
        },
        api: {
            bindevent: function () {
                Form.api.bindevent($("form[role=form]"));
            },
            formatter: {
                tag: function (value, row, index) {
                    console.log(value)
                    value = value === null ? '' : value.toString();
                    console.log(value)
                    //渲染Type
                    var html = [];
                    var arr = value.split(',');
                    $.each(arr, function (i, value) {
                        value = value === null ? '' : value.toString();
                        if (value == '')
                            return true;
                        var color = 'primary';
                        var display = value;
                        if (display != null && display != '' && display != '-') {
                            html.push('<a title="详情" class="labelhref" href="#" name="' + display + '"><span class="label label-' + color + '" style="font-size:90%;">' + display + '</span></a>');
                        } else {
                            html.push('<span class="label label-' + color + '" style="font-size:90%;">' + display + '</span>');
                        }
                    });
                    return html.join(' ');
                },

            }
        }
    };
    return Controller;
});